package com.woniu51.auth.service.impl;

import com.woniu.common.constant.Constants;
import com.woniu.common.core.domain.model.LoginBody;
import com.woniu.common.core.redis.RedisCache;
import com.woniu.common.enums.ExceptionCode;
import com.woniu.common.exception.CustomException;
import com.woniu.common.utils.token.JwtTokenUtils;
import com.woniu51.api.UserFeignClient;
import com.woniu51.auth.service.AuthService;
import com.woniu51.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 杨光
 * @date 2022年03月29日 11:49
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String doLogin(LoginBody loginBody) {

        //1.检查用户输入的验证码是否正确
        String verifyKey = Constants.CAPTCHA_CODE_KEY + loginBody.getUuid();
        Object code = redisCache.getCacheObject(verifyKey);
        if(code==null || !loginBody.getCode().equals(code.toString())){
            throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }

        //2.检查用户输入的用户 名和密码是否正确
        User user = userFeignClient.queryUserByUserAccountAndPassword(loginBody.getUsername(), loginBody.getPassword());
        if(user==null){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }

        //3.登录成功，生成jwttoken
        String jwt = JwtTokenUtils.generateAdminJwtToken(user.getUserId(),user.getUserName(),user.getUserAccount());

        System.out.println(user);
        return jwt;
    }

    @Override
    public String doWebLogin(LoginBody loginBody) {

        //检查用户名和密码是否正确
        User user = userFeignClient.queryUserByUserAccountAndPassword(loginBody.getUsername(), loginBody.getPassword());
        if(user==null){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }

        //3.登录成功，生成jwttoken
        String jwt = JwtTokenUtils.generateWebJwtToken(user.getUserId(),user.getUserName(),user.getUserAccount());

        System.out.println(user);
        return jwt;
    }
}
